<template>
  <Panel>
    <template #title>
      <p>账号列表</p>
    </template>
    <template #content>
      <div>
        <!-- 1.0 批量删除的组件 -->
        <el-row>
          <el-col>
            <el-button type="danger" size="mini" @click="delMore"
              >批量删除</el-button
            >
            <el-button type="primary" size="mini">取消选择</el-button>
          </el-col>
        </el-row>

        <!-- 2.0 渲染用户表格 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          size="mini"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="account" label="姓名" width="120">
          </el-table-column>
          <el-table-column prop="userGroup" label="用户组" width="120">
          </el-table-column>
          <el-table-column label="创建日期">
            <template v-slot="{ row }">
              {{ row.ctime | getTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip>
            <template v-slot="{ row }">
              <el-button type="primary" size="mini" @click="editUser(row)"
                >编辑</el-button
              >
              <el-button type="danger" size="mini" @click="delUser(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 3.0 分页渲染 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[2, 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>

        <!-- 4.0 编辑的弹框 -->
        <el-dialog title="编辑账号" :visible.sync="dialogVisible" width="50%">
          <!-- 4.1 布局的盒子写在上面 -->
          <div>
            <el-form
              :model="editForm"
              status-icon
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
              size="mini"
            >
              <el-form-item label="用户名" prop="username">
                <el-input
                  type="text"
                  v-model="editForm.username"
                  autocomplete="off"
                  style="width: 193px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="用户组" prop="selectVal">
                <el-select v-model="editForm.selectVal" placeholder="请选择">
                  <el-option
                    v-for="item in userGroup"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <!-- 4.2 底下是操作的按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="mini"
              >取 消</el-button
            >
            <el-button type="primary" @click="sureEdit" size="mini"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </template>
  </Panel>
</template>

<script>
import moment from 'moment'
import { validateUserName } from '@/utils/validate.js'
import {
  getUserList,
  delAccount,
  deleteMore,
  editAccount
} from '../../api/users.js'

export default {
  data() {
    const select = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择用户角色'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      // 批量删除使用的数组
      ids: [],
      dialogVisible: false,
      userGroup: [
        { value: '普通管理员', label: '普通管理员' },
        { value: '超级管理员', label: '超级管理员' }
      ],
      editForm: {
        username: '',
        selectVal: ''
      },
      rules: {
        username: [{ validator: validateUserName, trigger: 'blur' }],
        selectVal: [{ validator: select, trigger: 'click' }]
      }
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    async getUsers() {
      // 当本地数据仅剩一条并且不是第一页的时候
      if (this.tableData.length <= 1 && this.currentPage !== 1) {
        this.currentPage--
      }
      const { data, total } = await getUserList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      console.log(data)
      this.tableData = data
      this.total = total
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 每一次用户选择都会触发
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.ids = []
      val.forEach(item => {
        this.ids.push(item.id)
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUsers()
    },
    delUser(id) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await delAccount({ id })
          console.log(data)
          if (data.code === 0) {
            this.getUsers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除
    delMore() {
      if (this.ids.length === 0) return
      this.$confirm('此操作一下子删除了很多, 确定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await deleteMore({ ids: JSON.stringify(this.ids) })
          console.log(data)
          if (data.code === 0) {
            // 在批量删除的成功请求里面同步的把本地数据清空
            this.ids.forEach(item => {
              const i = this.tableData.findIndex(sub => sub.id === item)
              this.tableData.splice(i, 1)
            })
            // 如果批量删除最后只剩一条数据，那我就先让 this.currentPage++
            if (this.tableData.length === 1) {
              this.currentPage++
            }
            this.getUsers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 修改账号
    editUser(obj) {
      this.editForm.id = obj.id
      this.editForm.username = obj.account
      this.editForm.selectVal = obj.userGroup
      this.dialogVisible = true
    },
    async sureEdit() {
      const data = await editAccount({
        id: this.editForm.id,
        account: this.editForm.username,
        userGroup: this.editForm.selectVal
      })

      if (data.code === 0) {
        this.getUsers()
        this.dialogVisible = false
      }
    }
  },
  filters: {
    getTime(val) {
      return moment(val).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin: 30px 0;
}
</style>
